﻿'use strict';

app.controller('GridController', ['$scope', '$timeout', 'listStorage', 'policeData',
                                  '$ListDataService', '$q', 'SPHandy',
                                  function ($scope, $timeout, listStorage, policeData, $ListDataService, $q, SPHandy) {
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    $scope.showMap = false;

    $scope.radioModel = 'New';
    $scope.status = "";
    $scope.appWebUrl = "";
    var listContents = {
        items: []
    };


    //I need to move all this google map stuff into a seperate controller 
    //not sure how yet, maybe it has a dependancy on this controller, or 
    //maybe all the data is stored in the service so the service instance has the data?
    //or maybe broadcast messages or I dunno will figure it out later.

    //I tried using the new version of angular google maps directives but it just wouldnt work
    //no idea why
    
    var mapOptions = {
        zoom: 15,
        center: new google.maps.LatLng(52.6143247,-1.6677285),
        mapTypeId: google.maps.MapTypeId.TERRAIN
    }

    var map = new google.maps.Map(document.getElementById('map'), mapOptions);
    var lastbouncingMarker = null;
    var infoWindow = new google.maps.InfoWindow();

    function createMarker(info) {

        var marker = new google.maps.Marker({
            map: map,
            position: new google.maps.LatLng(info.Lat, info.Long),
            title: info.Street
        });
        marker.content = '<div class="infoWindowContent">' + info.Category + '</div>';

        google.maps.event.addListener(marker, 'click', function () {
            infoWindow.setContent('<b>' + marker.title + '</b>' + marker.content);
            infoWindow.open(map, marker);
        });

        info.marker=marker;

    }

    function deleteMarkers() {
        for (var i = 0; i < listContents.items.length; i++) {
            listContents.items.markers[i].setMap(null);
            delete listContents.items.markers;
        }
    }

 
    $scope.openInfoWindow = function (e, selectedMarker) {
        e.preventDefault();
        google.maps.event.trigger(selectedMarker, 'click');
    }



    $scope.listContents = listContents;

    //ng-grid hack to rest column defs on refresh of data
    $scope.colDefs = [];

    $scope.$watch('listContents.items', function () {
        $scope.colDefs = [];
        if ($scope.listContents.items.length > 0) {
            angular.forEach(Object.keys($scope.listContents.items[0]), function (key) {
                if (key !== "marker") {
                    $scope.colDefs.push({ field: key });
                }
            });
        }
    });

    var selectedItem = [];
    $scope.gridOptions = {
        data: 'listContents.items',
        columnDefs: 'colDefs',
        enablePaging: false,
        showFooter: true,
        enableRowSelection: true,
        multiSelect: false,
        showGroupPanel: true,
        pagingOptions: $scope.pagingOptions,
        enableColumnResize: false,  //Has to be false cos of hack
        filterOptions: $scope.filterOptions,
        selectedItems:selectedItem,
        afterSelectionChange: rowChanged
    };

    

    if (is_chrome) {
        $scope.gridOptions.plugins = [new ngGridCsvExportPlugin()];
    }


    function delayHighlightMarker(marker) {
        //This is here because of timing issues on first displaying the map.  
        //The map may not render before it starts a highlight process.
        $timeout(function () {
            google.maps.event.trigger(map, 'resize');
            highlightMarker(marker);
        }, 500);
    }

    function highlightMarker(marker)
    {
        //If you click before the other one has stopped bouncing
        //You need to cancel the timer (else if you swap between 2 over and over it has weird results)
        //Then stop it bouncing before starting the new one
        if (lastbouncingMarker)
        {
            $timeout.cancel(lastbouncingMarker.timer); 
            lastbouncingMarker.marker.setAnimation(null);
            lastbouncingMarker = null;
        }

        map.panTo(marker.getPosition());
        lastbouncingMarker = {};
        lastbouncingMarker.marker = marker;
        
        marker.setAnimation(google.maps.Animation.BOUNCE);
        lastbouncingMarker.timer = $timeout(function () {
            marker.setAnimation(null);
        }, 3000);

    }

    function rowChanged(rowItem, event){
        if (rowItem.entity.hasOwnProperty("marker") )
        {
            var marker = rowItem.entity.marker;
            highlightMarker(marker);
        }
    }

    $scope.initialise = function () {
        //Initialisation startup Get All Sites and bind on promise
        $scope.appWebUrl = decodeURIComponent(
                         SPHandy.getQueryStringParameter("SPAppWebUrl")
                    );

        $scope.listRefresh();
      
    }

    $scope.listRefresh = function () {
        $scope.status = "Fetching Data";
        $scope.inProcess = true;


        $scope.listContents.items = [];

        var getItems;
        $scope.showMap = false;

        deleteMarkers();

        switch ($scope.radioModel)
        {
            case "LegacyNew":
                getItems = $ListDataService.getItemsNew;
                break;
            case "Legacy":
                getItems = $ListDataService.getItems;
                break;
            case "Police":
                getItems = policeData.getForces;
                break;
            case "PoliceCrime":
                getItems = policeData.getStreetCrime;
                $scope.showMap = null;
                break;
            case "SPServices":
                getItems = listStorage.getItemsSPServices;
                break;
            case "Resource":
                //I Removed this using $resource returns an array of resource objects so that RESTful
                //and I couldnt make it work :-)
                
            default:
                getItems = listStorage.getItems;
                break;
        }

        var promise = getItems($scope);

        promise.then(
    		function (data) {
    		    $scope.listContents.items = data;
    		    $scope.status = "";
    		    if ($scope.showMap==null)
    		    {
    		        $scope.showMap = true;
    		        //problem with maps and ng-show doesnt set map boundaries properly
                    //so force a redraw
    		        
    		        angular.forEach($scope.listContents.items, function (crimeItem) {
    		            createMarker(crimeItem);
    		        });

                    
    		        if ($scope.listContents.items.length > 0) {
    		            delayHighlightMarker($scope.listContents.items[0].marker);
    		        }
    		    }

    		    $scope.inProcess = false;

    		},
			function (error) {
			    if ($scope.showMap == null) {
			        $scope.showMap = false;
			    }
			    $scope.status = "Error failed to get data:" + error;
			    $scope.inProcess = false;
			}
	    );

    }

    //run Initialise process at beginning

    $scope.initialise();


}]);

